<?php

namespace App\Http;

use \App\Helpers\Utils;

/**
 * HTTP响应环境类
 * @package App\Http
 */
class Response extends \Phalcon\Http\Response {

    /**
     * 响应数据配置数组
     * @var array
     */
    private $_lang = array();

    /**
     * 设置响应数据配置数组
     * @param string $name 文件名称
     * @param string $ver 版本文件夹
     */
    function setLang($name, $ver = "") {
        $this->_lang = Utils::readLanguage($name, $ver);
    }

    #region 请求响应相关

    /**
     * 发送带有数据的响应
     * @param array $data 响应数据
     * @param int $state Http Http响应状态码
     * @param int $code Http Http响应状态码
     */
    function sendResponseData(array $data, $state = 10000, $code = 200) {
        $content = $this->getResponseContent($state);
        $content = array_merge($data, $content);
        $this->sendResponseContent($content, $code);
    }

    /**
     * 根据自定义响应状态码发送响应
     * @param int $state 自定义响应状态码
     * @param int $code Http响应状态码
     */
    function sendResponse($state = 10000, $code = 200) {
        $content = $this->getResponseContent($state);
        $this->sendResponseContent($content, $code);
    }

    /**
     * 发送响应
     * @param array $content 自定义响应状态
     * @param int $code Http响应状态码
     */
    function sendResponseContent($content, $code = 200) {

        /**
         * @var \App\Helpers\CryptHelper $cryptHelper 加解密帮助对象
         */

        $message = $this->getHttpCodeContent($code);
        $this->setStatusCode($code, $message)
            ->setJsonContent($content, JSON_UNESCAPED_UNICODE);
    }

    /**
     * 获取响应的自定义状态内容
     * @param $state 响应自定义状态码
     * @return array
     */
    function getResponseContent($state) {
        if (!$this->_lang) {
            $this->setLang("responseCode", "");
        }
        return array(
            "status_code" => $state,
            "message" => $this->_lang[$state]
        );
    }

    /**
     * 获取Http响应状态描述
     * @param $code Http响应状态码
     */
    function getHttpCodeContent($code) {
        static $httpCode;
        if (!isset($httpCode)) {
            $httpCode = Utils::configItem("httpCode")->toArray();
        }
        return $httpCode[$code];
    }

    #endregion
}